package com.mouse.hxsj.util;

import javax.swing.*;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ViewGet {
    public static String textField(JTextField jTextField) {
        return jTextField.getText();
    }

    public static <T> T textField(JTextField jTextField, Class<T> tClass) {
        String text = jTextField.getText();
        if (StringUtil.isBlank(text)) return null;
        if (tClass.equals(String.class)) return (T)text;
        return JsonUtil.getObject(text, tClass);
    }
    public static Object comboBox(JComboBox comboBox, String key) {
        return comboBox(comboBox, key,"");
    }
    public static Object comboBox(JComboBox comboBox, String key,String defaultValue) {
        Object item = comboBox.getSelectedItem();
        if (item == null) return defaultValue;
        if (item instanceof String) return item;
        Class<?> aClass = item.getClass();
        List<Field> fieldList = Arrays.stream(aClass.getDeclaredFields()).filter(field -> field.getName().equals(key)).collect(Collectors.toList());
        if (fieldList.size() == 0) return null;
        Field field = fieldList.get(0);
        field.setAccessible(true);
        Object o = null;
        try {
            o = field.get(item);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return o;
    }

    public static <T> T comboBox(JComboBox comboBox, String key, Class<T> clas) {
        Object item = comboBox.getSelectedItem();
        if (item == null) return null;
        if (item instanceof String) return (T)item.toString();
        Class<?> aClass = item.getClass();
        List<Field> fieldList = Arrays.stream(aClass.getDeclaredFields()).filter(field -> field.getName().equals(key)).collect(Collectors.toList());
        if (fieldList.size() == 0) return null;
        Field field = fieldList.get(0);
        field.setAccessible(true);
        Object o = null;
        try {
            o = field.get(item);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        if (o == null) return null;
        return JsonUtil.getObject(o.toString(), clas);
    }
}
